package com.epalmpay.job;

import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.service.jobservice.IMemberRedActivityTaskService;
import com.epalmpay.service.operator.ISysLogService;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by gwn on 2018/1/23.
 */
@Component
public class MemberRedActivityJob {

    @Resource
    private ISysLogService sysLogService;

    @Resource
    private IMemberRedActivityTaskService memberRedActivityTaskService;

    protected Logger logger = Logger.getLogger(this.getClass());

    /**
     * 会员红利返利计划任务
     * 每天凌晨1点执行一次
     */
    @Scheduled(cron="0 0 1 * * ?")
    public void  run(){

        //统计日期
        Date statisDate = null;
        StringBuffer sb = new StringBuffer();
        try {
            //取得昨天日期
            //statisDate = DateUtil.getAfterDay(-1);
            statisDate = new Date();

            memberRedActivityTaskService.saveMemberRedActivityPerfectDayTask(statisDate);
            logger.info(sb.append("计划任务:")
                    .append(CommonEnum.TaskType.MemberRedActivityTask.getName())
                    .append("统计日期：").append(DateUtil.fomatDate(statisDate, DateUtil.sdfDays)).append("执行成功！"));

        } catch (ApplicationException ae) {
            logger.info(sb.append("计划任务:")
                    .append(CommonEnum.TaskType.MemberRedActivityTask.getName())
                    .append("统计日期：").append(DateUtil.fomatDate(statisDate, DateUtil.sdfDays)).append("执行结果：").append(ae.errMsg));
        }
        catch (Exception e) {
            try{
                sysLogService.recordSysTaskLog(CommonEnum.TaskType.MemberRedActivityTask.getType(),
                        statisDate, CommonEnum.RunStatus.Fail.getType());
            }catch(Exception sube){
                logger.info(sb.append("计划任务:")
                        .append(CommonEnum.TaskType.MemberRedActivityTask.getName())
                        .append("统计日期：").append(DateUtil.fomatDate(statisDate, DateUtil.sdfDays)).append("执行失败！"));
                logger.error(sube);
            }
            e.printStackTrace();
            logger.info(sb.append("计划任务:")
                    .append(CommonEnum.TaskType.MemberRedActivityTask.getName())
                    .append("统计日期：").append(DateUtil.fomatDate(statisDate, DateUtil.sdfDays)).append("执行失败！"));
            logger.error(e);
        }
    }
}


